//
//  YFTagView.m
//  project
//
//  Created by yefei on 2019/4/11.
//  Copyright © 2019 健健. All rights reserved.
//

#import "YFTagView.h"
#import "YFTagModel.h"
#import "UIImageView+WebCache.h"

#define TAG_LABEL_WIDTH ((SCREEN_WIDTH - 156) / 5)
#define TAG_LABEL_HEIGHT (20)

@interface YFTagView ()

#pragma mark - 标签类型

@property (weak, nonatomic) IBOutlet UIImageView *tagTypeImageView1;
@property (weak, nonatomic) IBOutlet UILabel *tagTypeLabel1;
@property (weak, nonatomic) IBOutlet UIImageView *tagTypeImageView2;
@property (weak, nonatomic) IBOutlet UILabel *tagTypeLabel2;
@property (weak, nonatomic) IBOutlet UIImageView *tagTypeImageView3;
@property (weak, nonatomic) IBOutlet UILabel *tagTypeLabel3;
@property (weak, nonatomic) IBOutlet UIImageView *tagTypeImageView4;
@property (weak, nonatomic) IBOutlet UILabel *tagTypeLabel4;

#pragma mark - 会生活
@property (weak, nonatomic) IBOutlet UIButton *lifeButton0;
@property (weak, nonatomic) IBOutlet UIButton *lifeButton1;
@property (weak, nonatomic) IBOutlet UIButton *lifeButton2;
@property (weak, nonatomic) IBOutlet UIButton *lifeButton3;
@property (weak, nonatomic) IBOutlet UIButton *lifeButton4;
@property (weak, nonatomic) IBOutlet UIButton *lifeButton5;

#pragma mark - 个性
@property (weak, nonatomic) IBOutlet UIButton *personallyButton0;
@property (weak, nonatomic) IBOutlet UIButton *personallyButton1;
@property (weak, nonatomic) IBOutlet UIButton *personallyButton2;
@property (weak, nonatomic) IBOutlet UIButton *personallyButton3;
@property (weak, nonatomic) IBOutlet UIButton *personallyButton4;
@property (weak, nonatomic) IBOutlet UIButton *personallyButton5;

#pragma mark - 性格
@property (weak, nonatomic) IBOutlet UIButton *characterButton0;
@property (weak, nonatomic) IBOutlet UIButton *characterButton1;
@property (weak, nonatomic) IBOutlet UIButton *characterButton2;
@property (weak, nonatomic) IBOutlet UIButton *characterButton3;
@property (weak, nonatomic) IBOutlet UIButton *characterButton4;
@property (weak, nonatomic) IBOutlet UIButton *characterButton5;

#pragma mark - 其他
@property (weak, nonatomic) IBOutlet UIButton *otherButton0;
@property (weak, nonatomic) IBOutlet UIButton *otherButton1;
@property (weak, nonatomic) IBOutlet UIButton *otherButton2;
@property (weak, nonatomic) IBOutlet UIButton *otherButton3;
@property (weak, nonatomic) IBOutlet UIButton *otherButton4;
@property (weak, nonatomic) IBOutlet UIButton *otherButton5;

/**
 button数组
 */
@property (nonatomic, strong) NSArray <UIButton *> *buttons1;
@property (nonatomic, strong) NSArray <UIButton *> *buttons2;
@property (nonatomic, strong) NSArray <UIButton *> *buttons3;
@property (nonatomic, strong) NSArray <UIButton *> *buttons4;
@property (nonatomic,strong) NSArray <NSArray *> *buttonArrays;
@property (nonatomic, strong) NSArray <UIImageView *> *tagTypeImageViews;
@property (nonatomic, strong) NSArray <UILabel *> *tagTypeNameLabels;



/**
 选中标签的背景 View
 */
@property (weak, nonatomic) IBOutlet UIView *selectedTagView;

/**
 选中标签的背景 View 高度约束
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *selectedTagViewConstraintHeight;

/**
 选择标签
 */
@property (weak, nonatomic) IBOutlet UILabel *placeholderLabel;

@end

@implementation YFTagView


- (void)awakeFromNib
{
    [super awakeFromNib];
    [self setupButtons];
}


- (void)setupButtons
{
    self.buttons1 = @[_lifeButton0, _lifeButton1, _lifeButton2, _lifeButton3, _lifeButton4, _lifeButton5];
    self.buttons2 = @[_personallyButton0, _personallyButton1, _personallyButton2, _personallyButton3, _personallyButton4, _personallyButton5];
    self.buttons3 = @[_characterButton0, _characterButton1, _characterButton2, _characterButton3, _characterButton4, _characterButton5];
    self.buttons4 = @[_otherButton0, _otherButton1, _otherButton2, _otherButton3, _otherButton4, _otherButton5];
//    self.tagTypeImageViews = @[_tagTypeImageView1, _tagTypeImageView2, _tagTypeImageView3, _tagTypeImageView4];
    self.tagTypeNameLabels = @[_tagTypeLabel1, _tagTypeLabel2, _tagTypeLabel3, _tagTypeLabel4];
    self.buttonArrays = @[_buttons1, _buttons2, _buttons3, _buttons4];
}

#pragma mark - 模型赋值
- (void)setTagModel:(YFTagModel *)tagModel {
    _tagModel = tagModel;
    
    // 设置选中的标签
    [self setupSelectedTags:_selectedTags];
    // 先隐藏所有的Button
    for (NSArray<UIButton *> *buttonArray in self.buttonArrays) {
        for (UIButton *button in buttonArray) {
            button.hidden = YES;
            button.backgroundColor = [UIColor whiteColor];
            [button setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        }
    }
    
    // 取出能设置的数量
    NSArray<YFTagType *> *tagTypeList = [NSArray array];
    if (tagModel.tagTypeList.count <= self.tagTypeNameLabels.count) {
        tagTypeList = tagModel.tagTypeList;
    } else {
        tagTypeList = [tagModel.tagTypeList subarrayWithRange:NSMakeRange(0, self.tagTypeNameLabels.count)];
    }
  
    for (int i = 0; i < tagTypeList.count; i++) {
        
        // 设置标签类型
        YFTagType *tagTypeModel = tagTypeList[i];
        self.tagTypeNameLabels[i].text = tagTypeModel.name;
        if (tagTypeModel.icon != nil && ![tagTypeModel.icon isEqualToString:@"<null>"] && ![tagTypeModel.icon isEqualToString:@"(null)"] && ![tagTypeModel.icon isEqualToString:@"null"]) {
            [self.tagTypeImageViews[i] sd_setImageWithURL:[NSURL URLWithString:tagTypeModel.icon]];
        }
        
        // 取出要设置的标签数组
        NSArray <UIButton *> *buttons = self.buttonArrays[i];
        
        // 取出能设置的数量
        NSArray <YFTag *> *tagList = [NSArray array];
        if (tagTypeModel.list.count <= buttons.count) {
            tagList = tagTypeModel.list;
        } else {
            tagList = [tagTypeModel.list subarrayWithRange:(NSMakeRange(0, buttons.count))];
        }
        
        
        for (int j = 0; j < tagList.count; j++) {
            
            // 设置标签
            // 取出模型
            YFTag *tagModel = tagList[j];
            // 取出数组
            UIButton *tagButton = buttons[j];
            
            //设置标签按钮
            [tagButton setTitle:tagModel.name forState:(UIControlStateNormal)];
            [tagButton setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
            // 设置样式
            [self setupShadowView:tagButton];
            tagButton.layer.cornerRadius = tagButton.height * 0.5;
            [tagButton addTarget:self action:@selector(tagButtonClicked:) forControlEvents:(UIControlEventTouchUpInside)];
            
            tagButton.hidden = NO;
            
            // 设置传值
            tagButton.tag = tagTypeModel.tagTypeId.integerValue * 10000 + tagModel.tagId.integerValue;
        }
    }
    [self setDefaultTags:[NSMutableArray arrayWithArray:[HJUserManager getUserModel].tagModels]];
    
}
- (void)setupShadowView:(UIView *)view {
    dispatch_async(dispatch_get_main_queue(), ^{
        CALayer *layer = [view layer];
        layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.06].CGColor;
        layer.shadowOffset = CGSizeMake(0,2);
        layer.shadowOpacity = 1;
        layer.shadowRadius = 4;
        layer.cornerRadius = view.height*0.5;
        UIBezierPath  *path = [UIBezierPath bezierPathWithRect:view.bounds];
        layer.shadowPath = path.CGPath;
    });
}

- (void)setDefaultTags:(NSArray<YFUserInfoTagModel *> *)defaultTags {
    LKLog(@"%s", __func__);
    _defaultTags = defaultTags;
    [self setupSelectedTags:defaultTags];
    
    for (YFUserInfoTagModel *model in defaultTags) {
        for (NSArray<UIButton *> *buttonArray in self.buttonArrays) {
            for (UIButton *button in buttonArray) {
                if ([button.titleLabel.text isEqualToString:model.name] && button.isSelected == NO) {
                    [button sendActionsForControlEvents:(UIControlEventTouchUpInside)];
                }
            }
        }
    }
}


#pragma mark - 按钮点击事件
- (void)tagButtonClicked:(UIButton *)button {
    
    if (self.selectedTags.count == 5 && button.isSelected == NO) {
        [YFHud showError:@"最多只能选择5个标签"];
        return ;
    }
    
    // 取出tagTypeId
    NSString *tagTypeId = [NSString stringWithFormat:@"%d", button.tag / 10000];
    
    // 取出tagId
    NSString *tagId = [NSString stringWithFormat:@"%d", button.tag % 10000];
    
    for (int i = 0; i < self.tagModel.tagTypeList.count; i++) {
        
        // 取出tagType
        YFTagType *tagTypeModel = self.tagModel.tagTypeList[i];
        
        if ([tagTypeModel.tagTypeId isEqualToString:tagTypeId]) {
            
            // 取出Buttons
            NSArray<UIButton *> *buttons = self.buttonArrays[i];
            
            // 遍历 Buttons
            @weakify(self)
            [buttons enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                @strongify(self)
                if (obj.tag == button.tag) {
                    
                    
                    if (obj.isSelected) {
                        [self setupShadowView:obj];
                        [obj setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
                        [obj setBackgroundColor:[UIColor whiteColor]];
                    } else {
                        [obj setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
                        [obj setBackgroundColor:[UIColor blackColor]];
                    }
                    obj.selected = !obj.selected;
                    [self saveSelectedTag:tagTypeId tagId:tagId name:button.titleLabel.text isSelected:button.isSelected color:@""];
                }
            }];
        }
    }
    
}

- (void)saveSelectedTag:(NSString *)tagTypeId tagId:(NSString *)tagId name:(NSString *)tagName isSelected:(BOOL)isSelected color:(NSString *)color {
    YFUserInfoTagModel *model = [[YFUserInfoTagModel alloc] init];
    model.tagId = tagId;
    model.name = tagName;
    model.color = color;
    
    NSMutableArray *selectedTagArray = [self.selectedTags copy];
    
    if (selectedTagArray.count == 0) {
        if (isSelected)
        [self.selectedTags addObject:model];
    } else {
        // 添加
        if (isSelected) {
            [self.selectedTags addObject:model];
        } else {
            // 移除
            for (YFUserInfoTagModel *tagModel in selectedTagArray) {
                if ([tagModel.tagId isEqualToString:tagId] && [tagModel.name isEqualToString:tagName]) {
                    [self.selectedTags removeObject:tagModel];
                }
            }
        }
    }
    
    LKLog(@"%@", self.selectedTags);
//
//    self.placeholderLabel.hidden = _selectedTags.count != 0;
    if (self.selectedTags.count==0) {
        self.placeholderLabel.text = @"请选择标签";
    }else {
        self.placeholderLabel.text = [NSString stringWithFormat:@"已选择标签%zd/5",self.selectedTags.count];
    }
    // 设置选中的标签
    [self setupSelectedTags:_selectedTags];
    
}

#pragma mark 设置选中 TagView
- (void)setupSelectedTags:(NSArray <YFUserInfoTagModel *> *)tagArray {
    
    // 清空子视图
    for (UIView *view in self.selectedTagView.subviews) {
        [view removeFromSuperview];
    }
    
    // 总列数
    NSInteger cols = (NSInteger)(SCREEN_WIDTH - 64) / (TAG_LABEL_WIDTH + 16);
    NSInteger rows = ceil((double)tagArray.count / cols);
    
    // 宽度、高度
    CGFloat tagWidth = TAG_LABEL_WIDTH;
    CGFloat tagHeight = 20;
    
    // 垂直方向间距
    CGFloat topMargin = (60 - 20) * 0.5;
    // 水平方向间距
    CGFloat leftMargin = 16;
    
    for (int i = 0; i < tagArray.count; i++) {
        
        // 标签所在的行
        NSInteger row = i / cols;
        // 标签所在的列
        NSInteger col = i % cols;
        
        CGFloat tagX = (leftMargin + tagWidth) * col;
        CGFloat tagY = topMargin + (topMargin + tagHeight) * row;

        UILabel *tagLabel = [[UILabel alloc] initWithFrame:CGRectMake(tagX, tagY, tagWidth, tagHeight)];
        tagLabel.textColor = [UIColor whiteColor];
        tagLabel.textAlignment = NSTextAlignmentCenter;
        tagLabel.font = [UIFont fontWithName:PingFangSC_Medium size:12];
        tagLabel.layer.masksToBounds = YES;
        tagLabel.layer.cornerRadius = tagHeight * 0.5;
//        tagLabel.alpha = 0;
        
        // 取模型
        YFUserInfoTagModel *model = tagArray[i];
        tagLabel.text = model.name;
        
        // 取颜色
         tagLabel.backgroundColor = [UIColor blackColor];
        [self.selectedTagView addSubview:tagLabel];
    }
    
    // 更新约束
    CGFloat selectTagViewHeight = topMargin + (tagHeight + topMargin) * rows;
    self.selectedTagViewConstraintHeight.constant = selectTagViewHeight > 60 ? selectTagViewHeight : 60;
    [UIView animateWithDuration:0.25 animations:^{
        [self layoutIfNeeded];
    }];
    
    // 更新自身高度
    if (_updateContentViewFrameAction) {
        CGFloat height = self.selectedTagViewConstraintHeight.constant + 104 * 4 + 4 + 24;
        CGFloat safeArea = STATUS_BAR_HEIGHT == 44 ? 34 : 0;
        height = height < SCREEN_HEIGTH - NAVIGATION_BAR_HEIGHT - safeArea ?  SCREEN_HEIGTH - NAVIGATION_BAR_HEIGHT - safeArea : height;
        _updateContentViewFrameAction(height);
    }
}

#pragma mark - Lazy Load
- (NSMutableArray <YFUserInfoTagModel *> *)selectedTags {
    if (!_selectedTags) {
        _selectedTags = [NSMutableArray arrayWithCapacity:3];
    }
    return  _selectedTags;
}



@end
